package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.exception.BizException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.*;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);  //操作数据库
         // 记录套餐和菜品关系
        //  套餐的id在哪呢
        if (setmealDto.getSetmealDishes()!=null && setmealDto.getSetmealDishes().size()>0) {
            setmealDto.getSetmealDishes().forEach(sd -> {
                sd.setSetmealId(setmealDto.getId());
            });
            setmealDishService.saveBatch(setmealDto.getSetmealDishes());  // 操作数据库
        }
    }

    @Override
    public Page<SetmealDto> pageSetmealWithCate(Integer page, Integer pageSize, String name) {
        //1. new page
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        // 2. 条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name),Setmeal::getName,name);
        // 排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        this.page(pageInfo,lqw);
        Page<SetmealDto> dtopage = new Page<>();
        // 拷贝
        BeanUtils.copyProperties(pageInfo,dtopage);
        // 空list
        List<SetmealDto> dtoList = new ArrayList<>();
        // 把list存入Records
        dtopage.setRecords(dtoList);

        // 大逻辑: 先把实体类的数据给赋值到dtolist集合里
        // 实体类list : setmeallist
        List<Setmeal> setmealslist = pageInfo.getRecords();
        // 提前先把对应的所有分类查出来
        // 先把分类的id准备好
        Set<Long> categoryIdSet = setmealslist.stream().map(Setmeal::getCategoryId).collect(Collectors.toSet());
        List<Category> categoryList = categoryMapper.selectBatchIds(categoryIdSet);
        // 把setmealslist 拷贝到dtolist里面
        setmealslist.forEach(s->{
            // 来复制实体类
            SetmealDto dto = new SetmealDto();
            BeanUtils.copyProperties(s,dto);
            dtoList.add(dto);

            // 匹配分类名称
            categoryList.forEach(c->{
                if (c.getId().equals(s.getCategoryId())){
                    dto.setCategoryName(c.getName());
                }
            });
        });

        return dtopage;
    }

    // 删除套餐
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeSetmealList(List<Long> ids) {
    // 判断一下 是否停售
        // select count(*) from setmeal where status = 0 and id in (?,?,?)
        int count = this.count(new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getStatus,1).in(Setmeal::getId,ids));
        // 大于0 代表在售 不让删
         if (count>0){
             throw new BizException("套餐有在售的,请先停售后再删除");

         }
         // 如果代码能走到这一行 说明都可以删
        // 先删套餐
        this.removeByIds(ids);
        // delete from setmeal_dish where setmeal_id in (1,2)
        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>()
                .in(SetmealDish::getSetmealId,ids));

    }

    @Override
    public List<Setmeal> getgeiSetmealList(Long categoryId, Integer status) {
        return  this.list(new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getCategoryId,categoryId).eq(Setmeal::getStatus,status));
    }

    // 批量起售
    @Override
    public void updateSetmeal1(List<Long> ids) {
        // update Dish set status = 1  where id in (?,?,?)
        LambdaUpdateWrapper<Setmeal> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Setmeal::getStatus,1).in(Setmeal::getId, ids);
        this.update(lqw);
    }

    // 批量停售
    @Override
    public void updateSetmeal0(List<Long> ids) {
        // update Dish set status = 0  where id in (?,?,?)
        LambdaUpdateWrapper<Setmeal> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Setmeal::getStatus,0).in(Setmeal::getId, ids);
        this.update(lqw);
    }

    // 修改套餐
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSetmeal(SetmealDto setmealDto) {

        this.updateById(setmealDto);

        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        // 删除套餐中相对应的菜品
        lqw.in(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(lqw);

        // 添加新的
        setmealDto.getSetmealDishes().forEach(f->{
            f.setSetmealId(setmealDto.getId());
        });
        this.setmealDishService.saveBatch(setmealDto.getSetmealDishes());
    }

    // 修改套餐显示
    @Override
    public SetmealDto getWithFlavor(Long id) {
        Setmeal setmeal = this.getById(id);
        // 拷贝
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        // 拷贝完了 还剩菜品
        List<SetmealDish> setmealDishes =setmealDishService
                .list(new LambdaQueryWrapper<SetmealDish>()
                        .eq(SetmealDish::getSetmealId,id ));
        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    // 点击套餐显示菜品
    @Override
    public List<SetmealDish> getDish(Long id) {

        List<SetmealDish> setmealDish =  new ArrayList<>();
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,id);
        setmealDish =  setmealDishService.list(lqw);
         // 拿到实体类的list
        //         List<Dish> dishList = this.list(lqw);
        return setmealDish;
    }

}
